#coding=utf-8
#Boa:FramePanel:PanelVoucher

import wx
import wx.grid

import DlgCustomerChoice
import DlgPopupSupplier

from config import *
from product import *
from ctrlAider import *

from MyListCtrl import MyListCtrlOrderAmountAllocted

import kit

[Type_Customer, Type_Supplier] = [i for i in range(2)]

[wxID_PANELVOUCHER, wxID_PANELVOUCHERBTNAUTOALLOCATE, 
 wxID_PANELVOUCHERBTNCANCEL, wxID_PANELVOUCHERBTNOK, 
 wxID_PANELVOUCHERBTNREFRESH, wxID_PANELVOUCHERBTNSHOWPEER, 
 wxID_PANELVOUCHERCBPAYWAY, wxID_PANELVOUCHERCBSTAFF, 
 wxID_PANELVOUCHERCHECKACCOUNT, wxID_PANELVOUCHERDATEBILL, 
 wxID_PANELVOUCHERGRID, wxID_PANELVOUCHERSTATICTEXT1, 
 wxID_PANELVOUCHERSTATICTEXT2, wxID_PANELVOUCHERSTATICTEXT3, 
 wxID_PANELVOUCHERTCDEBT, wxID_PANELVOUCHERTCMEMO, wxID_PANELVOUCHERTCMONEY, 
 wxID_PANELVOUCHERTCPARTNER, wxID_PANELVOUCHERTCUNALLOCATED, 
 wxID_PANELVOUCHERTCVOUCHERID, wxID_PANELVOUCHERTDATE, wxID_PANELVOUCHERTDEBT, 
 wxID_PANELVOUCHERTMEMO, wxID_PANELVOUCHERTMONEY, wxID_PANELVOUCHERTPARTNER, 
 wxID_PANELVOUCHERTPAYWAY, wxID_PANELVOUCHERTSTAFF, wxID_PANELVOUCHERTTITLE, 
 wxID_PANELVOUCHERTVOUCHERID, 
] = [wx.NewId() for _init_ctrls in range(29)]

class PanelVoucher(wx.Panel):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Panel.__init__(self, id=wxID_PANELVOUCHER, name=u'PanelVoucher',
              parent=prnt, pos=wx.Point(42, 55), size=wx.Size(1246, 631),
              style=wx.TAB_TRAVERSAL)
        self.SetClientSize(wx.Size(1238, 597))
        self.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False,
              u'\u6977\u4f53_GB2312'))
        self.SetBackgroundColour(wx.Colour(183, 209, 173))

        self.tPartner = wx.StaticText(id=wxID_PANELVOUCHERTPARTNER,
              label=u'\u9009\u62e9\u5ba2\u6237\uff1a', name=u'tPartner',
              parent=self, pos=wx.Point(88, 96), size=wx.Size(85, 16), style=0)

        self.tcPartner = wx.TextCtrl(id=wxID_PANELVOUCHERTCPARTNER,
              name=u'tcPartner', parent=self, pos=wx.Point(176, 88),
              size=wx.Size(208, 24), style=0, value=u'')

        self.btnShowPeer = wx.Button(id=wxID_PANELVOUCHERBTNSHOWPEER,
              label=u'+', name=u'btnShowPeer', parent=self, pos=wx.Point(384,
              88), size=wx.Size(24, 26), style=0)
        self.btnShowPeer.Bind(wx.EVT_BUTTON, self.OnBtnShowPeerButton,
              id=wxID_PANELVOUCHERBTNSHOWPEER)

        self.tcDebt = wx.TextCtrl(id=wxID_PANELVOUCHERTCDEBT, name=u'tcDebt',
              parent=self, pos=wx.Point(176, 128), size=wx.Size(128, 24),
              style=0, value=u'0.0')
        self.tcDebt.SetEditable(False)
        self.tcDebt.Enable(False)

        self.tDebt = wx.StaticText(id=wxID_PANELVOUCHERTDEBT,
              label=u'\u603b\u6b20\u6b3e\uff1a', name=u'tDebt', parent=self,
              pos=wx.Point(88, 136), size=wx.Size(68, 16), style=0)

        self.tMoney = wx.StaticText(id=wxID_PANELVOUCHERTMONEY,
              label=u'\u6536\u6b3e\u91d1\u989d\uff1a', name=u'tMoney',
              parent=self, pos=wx.Point(88, 176), size=wx.Size(85, 16),
              style=0)

        self.tcMoney = wx.TextCtrl(id=wxID_PANELVOUCHERTCMONEY, name=u'tcMoney',
              parent=self, pos=wx.Point(176, 168), size=wx.Size(128, 24),
              style=0, value=u'0.0')
        self.tcMoney.Bind(wx.EVT_TEXT, self.OnTcMoneyText,
              id=wxID_PANELVOUCHERTCMONEY)

        self.cbPayWay = wx.ComboBox(choices=[], id=wxID_PANELVOUCHERCBPAYWAY,
              name=u'cbPayWay', parent=self, pos=wx.Point(176, 208),
              size=wx.Size(130, 24), style=0, value=u'')
        self.cbPayWay.SetLabel(u'')

        self.tPayWay = wx.StaticText(id=wxID_PANELVOUCHERTPAYWAY,
              label=u'\u6536\u6b3e\u65b9\u5f0f\uff1a', name=u'tPayWay',
              parent=self, pos=wx.Point(88, 216), size=wx.Size(85, 16),
              style=0)

        self.staticText1 = wx.StaticText(id=wxID_PANELVOUCHERSTATICTEXT1,
              label=u'\u9009\u62e9\u6307\u5b9a\u5355\u636e\uff1a',
              name='staticText1', parent=self, pos=wx.Point(88, 256),
              size=wx.Size(119, 16), style=0)

        self.grid = wx.grid.Grid(id=wxID_PANELVOUCHERGRID, name=u'grid',
              parent=self, pos=wx.Point(88, 280), size=wx.Size(560, 192),
              style=0)
        self.grid.Bind(wx.grid.EVT_GRID_CELL_CHANGE, self.OnGridGridCellChange)

        self.staticText2 = wx.StaticText(id=wxID_PANELVOUCHERSTATICTEXT2,
              label=u'\u672a\u5206\u914d\u91d1\u989d\uff1a', name='staticText2',
              parent=self, pos=wx.Point(432, 256), size=wx.Size(102, 16),
              style=0)

        self.tcUnallocated = wx.TextCtrl(id=wxID_PANELVOUCHERTCUNALLOCATED,
              name=u'tcUnallocated', parent=self, pos=wx.Point(544, 248),
              size=wx.Size(104, 24), style=0, value=u'0.0')
        self.tcUnallocated.SetEditable(False)
        self.tcUnallocated.Enable(False)

        self.tStaff = wx.StaticText(id=wxID_PANELVOUCHERTSTAFF,
              label=u'\u7ecf\u529e\u4eba\uff1a', name=u'tStaff', parent=self,
              pos=wx.Point(408, 168), size=wx.Size(72, 14), style=0)

        self.cbStaff = wx.ComboBox(choices=[], id=wxID_PANELVOUCHERCBSTAFF,
              name=u'cbStaff', parent=self, pos=wx.Point(504, 160),
              size=wx.Size(138, 24), style=0, value=u'')

        self.tDate = wx.StaticText(id=wxID_PANELVOUCHERTDATE,
              label=u'\u65e5\u671f\uff1a', name=u'tDate', parent=self,
              pos=wx.Point(408, 64), size=wx.Size(64, 14), style=0)

        self.dateBill = wx.DatePickerCtrl(id=wxID_PANELVOUCHERDATEBILL,
              name=u'dateBill', parent=self, pos=wx.Point(496, 56),
              size=wx.Size(136, 22), style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)
        self.dateBill.SetLabel(u'2013-11-27')
        self.dateBill.SetValue(wx.DateTimeFromDMY(27, 10, 2013, 0, 0, 0))
        self.dateBill.SetWindowVariant(wx.WINDOW_VARIANT_NORMAL)
        self.dateBill.Bind(wx.EVT_DATE_CHANGED, self.OnDateBillDateChanged,
              id=wxID_PANELVOUCHERDATEBILL)

        self.tVoucherId = wx.StaticText(id=wxID_PANELVOUCHERTVOUCHERID,
              label=u'\u5355\u53f7\uff1a', name=u'tVoucherId', parent=self,
              pos=wx.Point(408, 32), size=wx.Size(64, 14), style=0)

        self.tcVoucherId = wx.StaticText(id=wxID_PANELVOUCHERTCVOUCHERID,
              label=u'P(GK)F-20140516-0001', name=u'tcVoucherId', parent=self,
              pos=wx.Point(496, 32), size=wx.Size(180, 16), style=0)

        self.tMemo = wx.StaticText(id=wxID_PANELVOUCHERTMEMO,
              label=u'\u5907\u6ce8\u4fe1\u606f\uff1a', name=u'tMemo',
              parent=self, pos=wx.Point(88, 488), size=wx.Size(85, 16),
              style=0)

        self.tcMemo = wx.TextCtrl(id=wxID_PANELVOUCHERTCMEMO, name=u'tcMemo',
              parent=self, pos=wx.Point(184, 480), size=wx.Size(448, 24),
              style=0, value=u'')

        self.btnOK = wx.Button(id=wxID_PANELVOUCHERBTNOK, label=u'\u786e\u5b9a',
              name=u'btnOK', parent=self, pos=wx.Point(248, 512),
              size=wx.Size(75, 24), style=0)
        self.btnOK.Bind(wx.EVT_BUTTON, self.OnBtnOKButton,
              id=wxID_PANELVOUCHERBTNOK)

        self.btnCancel = wx.Button(id=wxID_PANELVOUCHERBTNCANCEL,
              label=u'\u53d6\u6d88', name=u'btnCancel', parent=self,
              pos=wx.Point(384, 512), size=wx.Size(75, 24), style=0)
        self.btnCancel.Bind(wx.EVT_BUTTON, self.OnBtnCancelButton,
              id=wxID_PANELVOUCHERBTNCANCEL)

        self.tTitle = wx.StaticText(id=wxID_PANELVOUCHERTTITLE,
              label=u'\u4f1a\u6b3e\u5355', name=u'tTitle', parent=self,
              pos=wx.Point(240, 32), size=wx.Size(63, 20), style=0)
        self.tTitle.SetFont(wx.Font(15, wx.SWISS, wx.NORMAL, wx.BOLD, False,
              u'\u6977\u4f53_GB2312'))

        self.btnRefresh = wx.Button(id=wxID_PANELVOUCHERBTNREFRESH,
              label=u'\u5237\u65b0\u5355\u636e', name=u'btnRefresh',
              parent=self, pos=wx.Point(208, 248), size=wx.Size(93, 26),
              style=0)
        self.btnRefresh.Bind(wx.EVT_BUTTON, self.OnBtnRefreshButton,
              id=wxID_PANELVOUCHERBTNREFRESH)

        self.checkAccount = wx.CheckBox(id=wxID_PANELVOUCHERCHECKACCOUNT,
              label=u'\u662f\u5426\u5728\u8be5\u8d26\u6237\u4e2d\u6dfb\n\u52a0\u4e00\u6761\u6536\u652f\u8bb0\u5f55',
              name=u'checkAccount', parent=self, pos=wx.Point(320, 200),
              size=wx.Size(280, 24), style=0)
        self.checkAccount.SetValue(False)

        self.staticText3 = wx.StaticText(id=wxID_PANELVOUCHERSTATICTEXT3,
              label=u'\u6ce8\u610f\uff1a\u8981\u624b\u52a8\u6d88\u9664\u4e0eexcel\u5bfc\u5165\u91cd\u590d\u7684\u8bb0\u5f55',
              name='staticText3', parent=self, pos=wx.Point(336, 224),
              size=wx.Size(317, 16), style=0)

        self.btnAutoAllocate = wx.Button(id=wxID_PANELVOUCHERBTNAUTOALLOCATE,
              label=u'\u81ea\n\u52a8\n\u5206\n\u914d', name=u'btnAutoAllocate',
              parent=self, pos=wx.Point(648, 280), size=wx.Size(32, 96),
              style=0)
        self.btnAutoAllocate.Bind(wx.EVT_BUTTON, self.OnBtnAutoAllocateButton,
              id=wxID_PANELVOUCHERBTNAUTOALLOCATE)

    def __init__(self, parent, type):
        self._init_ctrls(parent)
        
        self.curType = type
        if(type == Type_Customer):
            self.ClsPeer = CDataCustomer
            self.ClsOrder = CDataSaleOrder
            self.ClsVoucher = CDataVoucher
            self.ClsFund = CRelFundCustomer
            
            self.pWin = DlgCustomerChoice.create(self)
            self.tcPeer = MyPopupTextCtrlDecorator(self.tcPartner, self.pWin)
            
        elif(type == Type_Supplier):
            self.ClsPeer = CDataSupplier
            self.ClsOrder = CDataPurOrder
            self.ClsVoucher = CDataVoucherSupplier
            self.ClsFund = CRelFundSupplier
            
            self.pWin = DlgPopupSupplier.create(self)
            self.tcPeer = MyPopupTextCtrlDecorator(self.tcPartner, self.pWin)
            
            self.tPartner.SetLabel(u'供货商：')
            self.tMoney.SetLabel(u'付款金额：')
            self.tPayWay.SetLabel(u'付款方式：')
            
        self.myInit()
    
    def myInit(self):
        self.m_peer = None
        
        self.dateBill.SetValue(wx.DateTime.Today())
        self.refreshId()
        
        self.cb = MyComboBoxDecorator(self.cbPayWay, CDataAccount, CDataAccount.COL_BRIEFNAME)
        self.cb.refresh()
        self.cb.SetValue(CDataAccount.getDefAccount())
        
        self.cbHandler = MyComboBoxDecorator(self.cbStaff, CDataStaff, CDataStaff.COL_NAME)
        self.cbHandler.refresh()
        self.cbHandler.SetValue(Cfg.getCurUser().getValue(CDataStaff.COL_NAME))
        
        self.initState()
        
        self.initGrid()
        
        self.accountDetailObj = None
        
    def initState(self):
        self.STATE_NEW = 0
        self.STATE_MODIFY = 1
        self.curState = self.STATE_NEW
        
        self.preVoucherId = ''
    
    def isModify(self):
        return self.curState == self.STATE_MODIFY
    
    def initGrid(self):
        titles = [(u'单据编号', 160), 
                    (u'总金额', 70), 
                    (u'已付', 70), 
                    (u'优惠',70), 
                    (u'未付',70),
                    (u'分配金额',80)]
        [self.COL_BILLID , self.COL_TOTAL, self.COL_PAID, self.COL_DISCOUNT,
        self.COL_UNPAID, self.COL_ALLOCT] = [i for i in range(len(titles))]
        
        self.grid.SetColLabelSize(32)
        self.grid.SetRowLabelSize(20)
         
        self.grid.CreateGrid(0, len(titles))
        for i in range(len(titles)):
            self.grid.SetColLabelValue(i, titles[i][0])
            self.grid.SetColSize(i, titles[i][1])
    
        
        # 设置可编辑cell的颜色，以便
        gridAttr = wx.grid.GridCellAttr()
        gridAttr.SetBackgroundColour(wx.Colour(255, 191, 191))
        self.grid.SetColAttr(self.COL_DISCOUNT, gridAttr)
        self.grid.SetColAttr(self.COL_ALLOCT, gridAttr)
        
    def getAlloctAmount(self):
        amount = float('0.0')
        for row in range(self.grid.GetNumberRows()):
            val = self.grid.GetCellValue(row, self.COL_ALLOCT)
            if (val != ''):
                amount += float(val)
        return amount
    
    def getAlloct(self, row):
        val = self.grid.GetCellValue(row, self.COL_ALLOCT)
        if (val != ''):
            return float(val)
        else:
            return 0.0
                
        
    def resetUnallocated(self):
        self.tcUnallocated.SetValue(str(self.getMoney()-self.getAlloctAmount()))
    
    def getMoney(self):
        return float(self.tcMoney.GetValue())
    
    def setFocusMoney(self):
        self.tcMoney.SetInsertionPointEnd()
        self.tcMoney.SetSelection(-1, -1)
        self.tcMoney.SetFocus()
    
    def setAccountDetail(self, id):
        accountDetailObj = CDataAccountDetail.getFirstInstance({CDataAccountDetail.COL_ID:id})
        accountId = accountDetailObj.getValue(accountDetailObj.COL_ACCOUNTID)
        accountObj = CDataAccount.getFirstInstance({CDataAccount.COL_ID:accountId})
        
        money = accountDetailObj.getValue(accountDetailObj.COL_MONEY)
        if (money < 0.0):
            if(self.curType != Type_Supplier):
                msg = u'该款项为支出，应该是向供货商付款，但是单据为收款单，请注意是否出错'
                dlg = wx.MessageDialog(self, msg,
                                    u'提示', wx.OK|wx.ICON_INFORMATION)
            
                dlg.ShowModal()
            else:
                money = -money
                    
        self.tcMoney.SetValue(kit.myStr(money))
        self.cb.SetValue(accountObj.getValue(accountObj.COL_BRIEFNAME))
        
        date = accountDetailObj.getValue(accountDetailObj.COL_DATE)
        self.dateBill.SetValue(wx.DateTimeFromDMY(date.day, date.month-1, date.year,0,0,0))
        self.refreshId()
        
        self.tcMoney.Disable()
        self.cbPayWay.Disable()
        self.dateBill.Disable()
        
        self.accountDetailObj = accountDetailObj
    
    def saveAccountDetail(self):
        self.accountDetailObj.setValue(self.accountDetailObj.COL_FUNDID, self.tcVoucherId.GetLabel())
        memo = self.accountDetailObj.getValue(self.accountDetailObj.COL_MEMO)
        memo += self.tcPeer.GetValue()
        self.accountDetailObj.setValue(self.accountDetailObj.COL_MEMO, memo)
        self.accountDetailObj.update()
    
    def getAccountId(self):
        accountObj = self.cb.getSelectObj()
        return accountObj.getValue(CDataAccount.COL_ID)
                
    def makeAccountDetail(self):
        money = float(self.tcMoney.GetValue())
        if (self.curType == Type_Supplier):
            money = -money
            
        date = self.dateBill.GetValue().Format('%Y-%m-%d') 
        memo = u'  【会款单：%s】' %self.tcPeer.GetValue()
        
        data = {CDataAccountDetail.COL_ACCOUNTID:self.getAccountId(),
                CDataAccountDetail.COL_DATE:date,
                CDataAccountDetail.COL_MONEY:money,
                CDataAccountDetail.COL_FUNDID:self.tcVoucherId.GetLabel(),
                CDataAccountDetail.COL_MEMO:memo}
                
        obj = CDataAccountDetail.createNew()
        obj.setMulFieldVal(data)
        obj.insert()
        
    def setAmount(self, money, accountObj):
        '''设置金额、方式'''
        self.tcMoney.SetValue(kit.myStr(money))
        
        #if (accountObj is not None):
        self.cb.SetValue(accountObj.getValue(accountObj.COL_BRIEFNAME))
                
    def setAllocate(self, row, money):
        '''设置指定行分配的金额，并高亮该行'''
        self.grid.SetCellValue(row, 5, kit.myStr(money))
                                
        for col in range(self.grid.GetNumberCols()):
            self.grid.SetCellBackgroundColour(row, col, wx.Colour(189, 151, 232))
    
    def clearAllocate(self):
        for row in range(self.grid.GetNumberRows()):
            self.grid.SetCellValue(row, 5, '')
            
    def refreshId(self):
        date = self.dateBill.GetValue().Format('%Y%m%d')
        self.tcVoucherId.SetLabel(self.ClsVoucher.newBillId(date))

    def refreshGridBill(self):
        numRows=self.grid.GetNumberRows()
        if(numRows > 0):
            self.grid.DeleteRows(numRows=numRows)
        
        list = self.ClsOrder.getBillAmount(self.m_peer.getValue(self.m_peer.COL_ID))
        for item in list:
            row = self.grid.GetNumberRows()
            self.grid.AppendRows()
            for col in range(len(item)):
                self.grid.SetCellValue(row, col, kit.myStr(item[col]))
    
    def setEditVoucher(self, voucherId):
        self.curState = self.STATE_MODIFY
        self.editedBillId = voucherId
        
        voucherObj = self.ClsVoucher.getFirstInstance({self.ClsVoucher.COL_ID:voucherId})
        
        peerId = voucherObj.getValue(voucherObj.COL_PEERID) 
        peerObj = self.ClsPeer.getFirstInstance({self.ClsPeer.COL_ID:peerId})
        
        money = voucherObj.getValue(voucherObj.COL_MONEY)
        memo = voucherObj.getValue(voucherObj.COL_MEMO)
                
        date = voucherObj.getValue(voucherObj.COL_DATE)
        if (isinstance(date, str) or isinstance(date, unicode)):
            import datetime
            date = datetime.datetime.strptime(date, '%Y-%m-%d')
        date = wx.DateTimeFromDMY(date.day, date.month-1, date.year,0,0,0)
        
        hId = voucherObj.getValue(voucherObj.COL_HANDLERID)
        hObj = CDataStaff.getFirstInstance({CDataStaff.COL_ID:hId})
        hName = hObj.getValue(CDataStaff.COL_NAME)
        
        accountId = voucherObj.getValue(voucherObj.COL_ACCOUNTID)
        accountObj = CDataAccount.getFirstInstance({CDataAccount.COL_ID:accountId})
        accountName = accountObj.getValue(CDataAccount.COL_BRIEFNAME)
        
        bills = voucherObj.getAllocateInfo()
        
        # 发送数据到界面
        self.setSelectPeer(peerObj)
        
        self.tcVoucherId.SetLabel(voucherId)
        self.dateBill.SetValue(date)
        self.cb.SetValue(accountName)
        self.cbHandler.SetValue(hName)
        self.tcMoney.SetValue(str(money))
        self.tcMemo.SetValue(memo)
                
        for billId,money in bills:
            for row in range(self.grid.GetNumberRows()):
                if (billId == self.grid.GetCellValue(row, self.COL_BILLID)):
                    # 修改显示的paid\unpaid
                    paid = float(self.grid.GetCellValue(row, self.COL_PAID)) - money
                    self.grid.SetCellValue(row, self.COL_PAID, kit.myStr(paid))
                    unpaid = float(self.grid.GetCellValue(row, self.COL_UNPAID)) + money
                    self.grid.SetCellValue(row, self.COL_UNPAID, kit.myStr(unpaid))
                    
                    self.setAllocate(row, money)
        
        self.resetUnallocated()
        
        self.setFocusMoney()
    
    def setSelectBill(self, billId):
        billObj = self.ClsOrder.getFirstInstance({self.ClsOrder.COL_ID:billId})
        peerId = billObj.getValue(billObj.COL_PEERID)
        peerObj = self.ClsPeer.getFirstInstance({self.ClsPeer.COL_ID:peerId})
        
        #unpaid = billObj.getValue(billObj.COL_UNPAID)
        unpaid = billObj.getUnpaid()
        if (unpaid <= 0.0):
            self.setSelectPeer(peerObj)
        else:
            msg = u'是否针对<%s>付款\n'\
                    u'--选是，为该付款单付款\n'\
                    u'--选否，为<%s>增加付款单' %(billId, peerObj.getValue(peerObj.COL_NAME))
            dlg = wx.MessageDialog(self, msg,
                                    u'提示', wx.YES_NO|wx.ICON_QUESTION)
            
            if(dlg.ShowModal() == wx.ID_YES):
                self.setSelectPeer(peerObj, False)
                total = billObj.getValue(billObj.COL_TOTAL)
                #paid = billObj.getValue(billObj.COL_PAID)
                paid = billObj.getPaid()
                disocunt = billObj.getValue(billObj.COL_DISCOUNT)
                #unpaid = billObj.getValue(billObj.COL_UNPAID)
        
                self.grid.AppendRows()
                self.grid.SetCellValue(0, 0, billId)
                self.grid.SetCellValue(0, 1, kit.myStr(total))
                self.grid.SetCellValue(0, 2, kit.myStr(paid))
                self.grid.SetCellValue(0, 3, kit.myStr(disocunt))
                self.grid.SetCellValue(0, 4, kit.myStr(unpaid))
                self.grid.SetCellValue(0, 5, kit.myStr(unpaid))
                                
                for col in range(self.grid.GetNumberCols()):
                    self.grid.SetCellBackgroundColour(0, col, wx.Colour(189, 151, 232))
                
                self.tcDebt.SetValue(kit.myStr(unpaid))
                self.tcMoney.SetValue(kit.myStr(unpaid))
                memo = u'为%s收款' %(billId)
                self.tcMemo.SetValue(memo)
                
            else:
                self.setSelectPeer(peerObj)
                
        self.setFocusMoney()
        
    def setSelectPeer(self, obj, showAllBill=True):
        self.m_peer = obj
        
        peerName = obj.getValue(obj.COL_NAME)
        self.tcPeer.ChangeValue(peerName)
        
        debt = obj.getDebt()
        self.tcDebt.SetValue(kit.myStr(debt))
                
        title = u'【款】%s' %peerName
        book = self.GetParent()
        self.GetParent().SetPageText(book.GetSelection(), title)
        
        if(showAllBill):
            self.refreshGridBill()

        self.setFocusMoney()
    
    def deletePreVoucher(self):
        self.ClsVoucher.deepDelData(self.editedBillId)
    
    def saveFund(self):
        if (self.grid.GetNumberRows() == 1):
            unpaid = float(self.grid.GetCellValue(0, self.COL_UNPAID))
            alloct = self.getAlloct(0)
            remain = unpaid - alloct
            if (remain > 0.0 and alloct > 0.0):
                msg = u'该订单仍欠 %g 元，是否对该订单优惠 %g 元？' %(remain, remain)
                dlg = wx.MessageDialog(self, msg,u'提示',wx.YES_NO|wx.ICON_QUESTION)
                if (dlg.ShowModal() == wx.ID_YES):
                    #self.grid.SetCellValue(0, self.COL_UNPAID, kit.myStr(0.0))
                    self.grid.SetCellValue(0, self.COL_DISCOUNT, kit.myStr(remain))
            
        voucherId =  self.tcVoucherId.GetLabel()
        for row in range(self.grid.GetNumberRows()):
            alloct = self.grid.GetCellValue(row, self.COL_ALLOCT)
            if (alloct == ''):
                continue
            
            alloct = float(alloct)
            if(alloct == 0.0):
                continue
            
            billId = self.grid.GetCellValue(row, self.COL_BILLID)
            data = {self.ClsFund.COL_BILLID:billId, 
                    self.ClsFund.COL_VOUCHERID:voucherId, 
                    self.ClsFund.COL_MONEY:alloct}
            obj = self.ClsFund()
            obj.setMulFieldVal(data)
            obj.insert()
            
            # 150314 - 取消order中的paid/unpaid，改为启动时计算，会造成启动效率影响，
            #            以后要把启动过程中的数据载入放在一个线程中处理
            #           因此不需要在收付款时，去修改order中的paid/unpaid，
            #           但是需要通知order对象重新计算paid/unpaid
            billObj = self.ClsOrder.getFirstInstance({self.ClsOrder.COL_ID:billId})
            billObj.populateExtra()
##            #update bill Paid/unpaid
##            billObj = self.ClsOrder.getFirstInstance({self.ClsOrder.COL_ID:billId})
##            # 编辑汇款单时，修改的alloct不能直接与数据库中加减
##            #paid = billObj.getValue(billObj.COL_PAID) + alloct
##            #unpaid = billObj.getValue(billObj.COL_UNPAID) - alloct
##            paid = float(self.grid.GetCellValue(row, self.COL_PAID)) + alloct
##            #unpaid = float(self.grid.GetCellValue(row, self.COL_UNPAID)) - alloct
##            discount = float(self.grid.GetCellValue(row, self.COL_DISCOUNT))
##            
##            # 需注意：unpaid须由 unpaid = total - paid - discount 计算
##            total = float(self.grid.GetCellValue(row, self.COL_TOTAL))
##            unpaid = total - paid - discount
##            
##            data = {self.ClsOrder.COL_PAID:paid,
##                    self.ClsOrder.COL_UNPAID:unpaid,
##                    self.ClsOrder.COL_DISCOUNT:discount}
##            billObj.setMulFieldVal(data)
##            billObj.update()        
            
    def saveVoucher(self):
        id = self.tcVoucherId.GetLabel()
        peerId = self.m_peer.getValue(self.m_peer.COL_ID)
        
        accountObj = self.cb.getSelectObj()
        accountId = accountObj.getValue(CDataAccount.COL_ID)
        
        money = float(self.tcMoney.GetValue())
        date = self.dateBill.GetValue().Format('%Y-%m-%d') 
        handlerId = self.cbHandler.getSelectObj().getValue(CDataStaff.COL_ID)
        recorderID = Cfg.getCurUser().getValue(CDataStaff.COL_ID)      
        memo = self.tcMemo.GetValue()
        
        data = {self.ClsVoucher.iId:id, 
                self.ClsVoucher.iPeerId:peerId, 
                self.ClsVoucher.iAccountId:accountId,
                self.ClsVoucher.iMoney:money, 
                self.ClsVoucher.iDate:date, 
                self.ClsVoucher.iHandlerId:handlerId,
                self.ClsVoucher.iRecorderId:recorderID, 
                self.ClsVoucher.iMemo:memo}
        obj = self.ClsVoucher()
        obj.setMulFieldVal(data)
        obj.insert()
            
    
                    
    def OnBtnShowPeerButton(self, event):
        self.tcPeer.resetPopupWinPos()
        self.pWin.Show()

    def OnDateBillDateChanged(self, event):
        self.refreshId()

    def OnBtnOKButton(self, event):
        if(self.m_peer is None or self.getMoney() <= 0.0):
            dlg = wx.MessageDialog(self, u'业务数据不完整，请核对数据',u'提示',wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            return
            
        unalloct = float(self.tcUnallocated.GetValue())
        if(unalloct < 0.0):
            msg = u'发生错误：分配金额大于收款金额，请重新设置分配金额'
            dlg = wx.MessageDialog(self, msg,u'提示',wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            return
        
        if (self.isModify()):
            msg = u'确认保存修改后的信息？'
            dlg = wx.MessageDialog(self, msg,u'提示',wx.YES_NO|wx.ICON_QUESTION)
            if(dlg.ShowModal() == wx.ID_NO):
                return
            
            self.deletePreVoucher()
            
        self.saveVoucher()
        self.saveFund()
        
        if self.accountDetailObj is not None:
            self.saveAccountDetail()

        if (self.checkAccount.GetValue() and self.accountDetailObj is None):
            self.makeAccountDetail()
            
        self.quit()

    def quit(self, doQuit=True):
        if doQuit:    
            book = self.GetParent()
            book.DeletePage(book.GetSelection())
        return True
    
    def doClose(self, doQuit=True):
        msg = u'是否继续退出当前业务操作?'
        dlg = wx.MessageDialog(self, msg,u'提示',wx.YES_NO|wx.ICON_QUESTION)
        if(dlg.ShowModal() == wx.ID_NO):
            return False
        return self.quit(doQuit)
        
        
    def OnBtnCancelButton(self, event):
        self.doClose()

    def OnTcMoneyText(self, event):
        #self.tcUnallocated.SetValue(str(self.getMoney()-self.getAlloctAmount()))
        self.resetUnallocated()

    def OnGridGridCellChange(self, event):
        if (event.GetCol() != self.COL_ALLOCT):
            msg = u'只允许修改分配金额'
            dlg = wx.MessageDialog(self, msg, u'提示', wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            return
        
        row = event.GetRow()
        for col in range(self.grid.GetNumberCols()):
            self.grid.SetCellBackgroundColour(row, col, wx.Colour(189, 151, 232))
            
        unalloct = self.getMoney() - self.getAlloctAmount()
        #self.tcUnallocated.SetValue(str(unalloct))
        self.resetUnallocated() 
        if(unalloct < 0.0):
            msg = u'发生错误：分配金额大于收款金额，请重新设置分配金额'
            dlg = wx.MessageDialog(self, msg,u'提示',wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            return

    def OnBtnRefreshButton(self, event):
        self.refreshGridBill()

    def OnBtnAutoAllocateButton(self, event):
        self.clearAllocate()
        money = self.getMoney()
        grid = self.grid
        for row in range(grid.GetNumberRows()-1, -1, -1):
            unpaid = float(grid.GetCellValue(row, self.COL_UNPAID))
            if (unpaid <= 0.0):
                continue
            
            if (money <= unpaid):
                self.setAllocate(row, money)
                break
            else:
                money -= unpaid
                self.setAllocate(row, unpaid)

        self.resetUnallocated()
